{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Transformers installation\n",
    "! pip install transformers datasets evaluate accelerate\n",
    "# To install from source instead of the last release, comment the command above and uncomment the following one.\n",
    "# ! pip install git+https://github.com/huggingface/transformers.git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Video-text-to-text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Video-text-to-text models, also known as video language models or vision language models with video input, are language models that take a video input. These models can tackle various tasks, from video question answering to video captioning.\n",
    "\n",
    "These models have nearly the same architecture as [image-text-to-text](https://huggingface.co/docs/transformers/main/en/tasks/../image_text_to_text) models except for some changes to accept video data, since video data is essentially image frames with temporal dependencies. Some image-text-to-text models take in multiple images, but this alone is inadequate for a model to accept videos. Moreover, video-text-to-text models are often trained with all vision modalities. Each example might have videos, multiple videos, images and multiple images. Some of these models can also take interleaved inputs. For example, you can refer to a specific video inside a string of text by adding a video token in text like \"What is happening in this video? `<video>`\".\n",
    "\n",
    "In this guide, we provide a brief overview of video LMs and show how to use them with Transformers for inference.\n",
    "\n",
    "To begin with, there are multiple types of video LMs:\n",
    "\n",
    "- base models used for fine-tuning\n",
    "- chat fine-tuned models for conversation\n",
    "- instruction fine-tuned models\n",
    "\n",
    "This guide focuses on inference with an instruction-tuned model, [llava-hf/llava-interleave-qwen-7b-hf](https://huggingface.co/llava-hf/llava-interleave-qwen-7b-hf) which can take in interleaved data. Alternatively, you can try [llava-interleave-qwen-0.5b-hf](https://huggingface.co/llava-hf/llava-interleave-qwen-0.5b-hf) if your hardware doesn't allow running a 7B model.\n",
    "\n",
    "Let's begin installing the dependencies.\n",
    "\n",
    "```bash\n",
    "pip install -q transformers accelerate flash_attn \n",
    "```\n",
    "\n",
    "Let's initialize the model and the processor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import LlavaProcessor, LlavaForConditionalGeneration\n",
    "import torch\n",
    "model_id = \"llava-hf/llava-interleave-qwen-0.5b-hf\"\n",
    "\n",
    "processor = LlavaProcessor.from_pretrained(model_id)\n",
    "\n",
    "model = LlavaForConditionalGeneration.from_pretrained(model_id, device_map=\"auto\", dtype=torch.float16)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some models directly consume the `<video>` token, and others accept `<image>` tokens equal to the number of sampled frames. This model handles videos in the latter fashion. We will write a simple utility to handle image tokens, and another utility to get a video from a url and sample frames from it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import uuid\n",
    "import requests\n",
    "import cv2\n",
    "from PIL import Image\n",
    "\n",
    "def replace_video_with_images(text, frames):\n",
    "  return text.replace(\"<video>\", \"<image>\" * frames)\n",
    "\n",
    "def sample_frames(url, num_frames):\n",
    "\n",
    "    response = requests.get(url)\n",
    "    path_id = str(uuid.uuid4())\n",
    "\n",
    "    path = f\"./{path_id}.mp4\" \n",
    "\n",
    "    with open(path, \"wb\") as f:\n",
    "      f.write(response.content)\n",
    "\n",
    "    video = cv2.VideoCapture(path)\n",
    "    total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))\n",
    "    interval = total_frames // num_frames\n",
    "    frames = []\n",
    "    for i in range(total_frames):\n",
    "        ret, frame = video.read()\n",
    "        pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n",
    "        if not ret:\n",
    "            continue\n",
    "        if i % interval == 0:\n",
    "            frames.append(pil_img)\n",
    "    video.release()\n",
    "    return frames[:num_frames]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's get our inputs. We will sample frames and concatenate them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "video_1 = \"https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_1.mp4\"\n",
    "video_2 = \"https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_2.mp4\"\n",
    "\n",
    "video_1 = sample_frames(video_1, 6)\n",
    "video_2 = sample_frames(video_2, 6)\n",
    "\n",
    "videos = video_1 + video_2\n",
    "\n",
    "videos\n",
    "\n",
    "# [<PIL.Image.Image image mode=RGB size=1920x1080>,\n",
    "# <PIL.Image.Image image mode=RGB size=1920x1080>,\n",
    "# <PIL.Image.Image image mode=RGB size=1920x1080>, ...]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both videos have cats.\n",
    "\n",
    "<div class=\"container\">\n",
    "  <div class=\"video-container\">\n",
    "    <video width=\"400\" controls>\n",
    "      <source src=\"https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_1.mp4\" type=\"video/mp4\">\n",
    "    </video>\n",
    "  </div>\n",
    "\n",
    "  <div class=\"video-container\">\n",
    "    <video width=\"400\" controls>\n",
    "      <source src=\"https://huggingface.co/spaces/merve/llava-interleave/resolve/main/cats_2.mp4\" type=\"video/mp4\">\n",
    "    </video>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "Now we can preprocess the inputs.\n",
    "\n",
    "This model has a prompt template that looks like following. First, we'll put all the sampled frames into one list. Since we have eight frames in each video, we will insert 12 `<image>` tokens to our prompt. Add `assistant` at the end of the prompt to trigger the model to give answers. Then we can preprocess."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_prompt = \"Are these two cats in these two videos doing the same thing?\"\n",
    "toks = \"<image>\" * 12\n",
    "prompt = \"<|im_start|>user\"+ toks + f\"\\n{user_prompt}<|im_end|><|im_start|>assistant\"\n",
    "inputs = processor(text=prompt, images=videos, return_tensors=\"pt\").to(model.device, model.dtype)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now call [generate()](https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.GenerationMixin.generate) for inference. The model outputs the question in our input and answer, so we only take the text after the prompt and `assistant` part from the model output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = model.generate(**inputs, max_new_tokens=100, do_sample=False)\n",
    "print(processor.decode(output[0][2:], skip_special_tokens=True)[len(user_prompt)+10:])\n",
    "\n",
    "# The first cat is shown in a relaxed state, with its eyes closed and a content expression, while the second cat is shown in a more active state, with its mouth open wide, possibly in a yawn or a vocalization."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And voila!\n",
    "\n",
    "To learn more about chat templates and token streaming for video-text-to-text models, refer to the [image-text-to-text](https://huggingface.co/docs/transformers/main/en/tasks/../tasks/image_text_to_text) task guide because these models work similarly."
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
